package com.xiaoyuan.minicore.mvc;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.xiaoyuan.minicore.core.ClassHelper;
import com.xiaoyuan.minicore.mvc.annotation.Request;
import com.xiaoyuan.minicore.mvc.bean.ActionBean;
import com.xiaoyuan.minicore.mvc.bean.BaseAction;
import com.xiaoyuan.minicore.mvc.bean.RequestBean;
import com.xiaoyuan.minicore.util.ArrayUtil;
import com.xiaoyuan.minicore.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Auther: xiaoyuan
 * @Date: 2020/4/28
 * @Description:
 */
public class ActionHelper {

    private static final Logger logger = LoggerFactory.getLogger(ActionHelper.class);

    private static final Map<RequestBean, ActionBean> actionMap = new HashMap<RequestBean, ActionBean>();



    public static void init() {
        // 获取并遍历所有 Action 类
        List<Class<?>> actionClassList = ClassHelper.getClassListBySuper(BaseAction.class);
        for (Class<?> actionClass : actionClassList) {
            // 获取并遍历该 Action 类中的所有方法（不包括父类中的方法）
            Method[] actionMethods = actionClass.getDeclaredMethods();
            if (ArrayUtil.isNotEmpty(actionMethods)) {
                for (Method actionMethod : actionMethods) {
                    // 判断当前 Action 方法是否带有 @Request 注解
                    if (actionMethod.isAnnotationPresent(Request.class)) {
                        // 获取 @Requet 注解中的 URL 字符串
                        String[] urlArray = actionMethod.getAnnotation(Request.class).value().split(":");
                        if (ArrayUtil.isNotEmpty(urlArray)) {
                            // 获取请求方法与请求 URL
                            String requestMethod = urlArray[0];
                            String requestURL = urlArray[1]; // 带有占位符
                            // 将请求路径中的占位符 {\w+} 转换为正则表达式 (\\w+)
                            requestURL = StringUtil.replaceAll(requestURL, "\\{\\w+\\}", "(\\\\w+)");
                            // 将 RequestBean 与 ActionBean 放入 Action Map 中
                            actionMap.put(new RequestBean(requestMethod, requestURL), new ActionBean(actionClass, actionMethod));
                            logger.info("load request [method={},url={},class={}.{}]",requestMethod, requestURL, actionClass.getName(),actionMethod.getName());
                        }
                    }
                }
            }
        }
        try {
            logger.info("共加载{}个Request",actionMap.size());
        }catch (Exception e){
            logger.error("error",e);
        }

    }

    public static Map<RequestBean, ActionBean> getActionMap() {
        return actionMap;
    }
}
